﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Ads;
using SIG.InputModel.Admin.Articles;
using SIG.Model;
using SIG.Model.Ads;
using SIG.Model.Articles;
using SIG.Model.Enums;
using SIG.Resources.Admin;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Ads;
using SIG.ViewModel.Admin.Articles;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PositionController : BaseController
    {
        private readonly IPositionService _positionService;
        private readonly IMapper _mapper;

        public PositionController(IPositionService positionService, IMapper mapper)
        {
            _positionService = positionService;
            _mapper = mapper;

        }
        // GET: Admin/Position

        #region Ad Position

        public ActionResult Index(int? page, string keyword)
        {
            PositionListVM positionListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(positionListVM);
            
        }

        private PositionListVM GetElements(int? page, string keyword)
        {
            var positionListVM = new PositionListVM();

            positionListVM.Keyword = keyword;
            positionListVM.PageIndex = (page ?? 1) - 1;
            positionListVM.PageSize = SettingsManager.Article.PageSize;
            int totalCount;
            var positionlist = _positionService.GetPagedElements(positionListVM.PageIndex, positionListVM.PageSize, positionListVM.Keyword, out totalCount);
            var positionVMList = _mapper.Map<List<Position>, List<PositionVM>>(positionlist);
            positionListVM.TotalCount = totalCount;
            positionListVM.Positions = new StaticPagedList<PositionVM>(positionVMList, positionListVM.PageIndex + 1, positionListVM.PageSize, positionListVM.TotalCount); ;
            return positionListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/AdsSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vPosition = new PositionIM();
            vPosition.Active = true;
            vPosition.Importance = 0;

            return PartialView("_Add", vPosition);
        }



        [HttpPost]
        public JsonResult Add(PositionIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newPosition = _mapper.Map<PositionIM, Position>(vm);
            _positionService.Create(newPosition);

            int count;
            var pageSize = SettingsManager.Article.PageSize;
            var list = _positionService.GetPagedElements(0, pageSize, string.Empty, out count);
            List<PositionVM> categories = _mapper.Map<List<Position>, List<PositionVM>>(list);
            AR.Data = RenderPartialViewToString("_PositionList", categories);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Position));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Position position = _positionService.GetById(id);
            if (position == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<PositionIM>(position);


            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(PositionIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newPosition = _mapper.Map<PositionIM, Position>(vm);
            _positionService.Update(newPosition);

    
     

            var position = _mapper.Map<PositionVM>(newPosition);
            AR.Id = position.Id;
            AR.Data = RenderPartialViewToString("_PositionItem", position);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Position));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Position vPosition = _positionService.GetById(id);

            if (vPosition.Carousels.Any())
            {
                AR.Setfailure("此分类下面还有广告存在，不能删除！");
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _positionService.Delete(vPosition);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Position));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vPosition = _positionService.GetById(id);
            if (vPosition == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vPosition.Active = !vPosition.Active;
                _positionService.Update(vPosition);

                var vm = _mapper.Map<PositionVM>(vPosition);

                AR.Data = RenderPartialViewToString("_PositionItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Position));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [AllowAnonymous]
        public JsonResult IsCodeUnique(string code, int? Id)
        {
            return !IsExist(code, Id)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public bool IsExist(string code, int? id)
        {
            var wType = _positionService.GetAll().Where(w => w.Code == code);
            if (id > 0)
            {
                wType = wType.Where(w => w.Id != id);
            }

            if (wType.Count() > 0)
                return true;

            return false;
        }



        #endregion
    }
}